<?php
namespace app\applet\controller;

use app\BaseController;
use app\service\alipayService;
use think\facade\Db;
use think\facade\Log;

class Trade extends BaseController{
    public function trade(){
        $gateid=request()->post("gate_id");
        $gateid="21";
        $money=request()->post("money");
        $gateinfo=Db::table("cxyun_parking_gate")->where("id",$gateid)->find();
        if(empty($gateinfo)){
            parent::sendOutput(['info' => '停车场配置不存在'],500);
        }
        $parkinglotinfo=Db::table("parkinglotinfo")->where("parkingNo",$gateinfo["parkingNo"])->find();
        if(empty($parkinglotinfo)){
            parent::sendOutput("停车场信息不存在",500);
        }


        $info["order_money"]=request()->post("money");
        $info["remark"]=request()->post("remark");
        $info["user_id"]=$this->request->openid;
        $info["parking_name"]=$gateinfo["parkingName"];
        $info["pay_money"]=$money;
        $info["out_trade_no"]=date('YmdHiss').rand(100000,999999);
        $info["subject"] = $gateinfo["parkingName"]."-".$gateinfo["gateName"];
        $info["parking_id"]=$gateinfo["parkingId"];
        $info["gate_name"]=$gateinfo["gateName"];
        $info["gate_id"]=$gateinfo["id"];


        $api = new alipayService();

        $notifyUrl=$this->getCurrentUrl()."/zftpay/callback/notice";

        $settle_detail_info=array(
            'trans_in_type'=>'defaultSettle',//'loginName',
            'trans_in'=>'',//收款账号aliwykd@163.com
            'amount'=>$info["pay_money"],//结算金额
        );
        $data= array(
            'out_trade_no'=> $info["out_trade_no"],
            'total_amount'=>$info["pay_money"],
            'buyer_id'=>$info["user_id"],//$info["user_id"],
            'subject' =>$info["subject"],
            'notifyurl'=>$notifyUrl,
            'token'=>$parkinglotinfo["accredit"],//$,
            'notifyUrl'=>$notifyUrl,
        );
        $result = $api->create(json_encode($data));
        Log::write($data);
        Log::write($result);
        if(property_exists($result,'sub_msg')){
            parent::sendOutput($result->sub_msg,500);
            return json(['info' => $result->sub_msg]);
        }else{
            $info['trade_no'] =  $result->trade_no;
            $data["trade_no"]=$info["trade_no"];
            parent::sendOutput($data);
            $res=Db::table("zft_order")->insert($info);
            //返回结果到前台唤起收银台
            if($res){

                //return json(['trade_no' => $info['trade_no']]);
            }else{
                return json(['info' => '订单存储失败',"code"=>500]);
            }
        }
    }
}